package pl.lodz.p.browarex.validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import pl.lodz.p.browarex.model.Product;

@Component
public class ProductValidation implements Validator{

	@Override
	public boolean supports(Class<?> type) {
		return  type == Product.class;
	}

	@Override
	public void validate(Object obj, Errors errors) {
		Product p = (Product) obj;
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bundle", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "capacity", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "voltage", "field.required");
		if ( ! errors.hasFieldErrors("price")) {
			if (p.getPrice().intValue() < 0 && p.getPrice().intValue()>500 )
				errors.rejectValue("price", "bad.field");
		}
		if ( ! errors.hasFieldErrors("voltage")) {
			if (p.getVoltage() < 0 && p.getVoltage()>10 )
				errors.rejectValue("voltage", "bad.field");
		}
		if ( ! errors.hasFieldErrors("capacity")) {
			if (p.getCapacity() < 0 )
				errors.rejectValue("capacity", "bad.field");
		}
	}

}
